﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Security.Authentication;
using System.Security.Principal;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.UI;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.BusinessLogic.Services;
using Newtonsoft.Json;
using System.Web.Script.Services;
using Legazpi.Payroll.DataAccess.DataObjects;
using Ninject;
using Ninject.Web;
using Legazpi.Payroll.Web.Helpers;
using Legazpi.Payroll.DataAccess.DataObjects.Enums;
using System.Threading;

namespace Legazpi.Payroll.Web.Webservices
{
    /// <summary>
    /// Summary description for EmployeeWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class EmployeeWebService : WebServiceBase

    {
        [Inject]
        public IEmployeeService _employeeService { get; set; }

        [Inject]
        public IPositionService _positionService { get; set; }

        [Inject]
        public IClientService _clientService { get; set; }

        [Inject]
        public IAdjustmentService _adjustmentService { get; set; }

        [Inject]
        public IEmployeeAdjustmentService _employeeAdjustmentService { get; set; }

        [Inject]
        public ISectorService _sectorService { get; set; }

        [Inject]
        public IDetachmentService _detachmentService { get; set; }


        #region Employees
        [WebMethod]
        public string AddEmployee(EmployeeObj employeeItem)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            var _employee = employeeItem.Id > 0 ? _employeeService.GetById(employeeItem.Id) : null;
            bool isAdded;
            DateTime tempDate;
            if (_employee != null)
            {
                //Update
                isAdded = false;
                _employee.FirstName = employeeItem.FirstName;
                _employee.MiddleName = employeeItem.MiddleName;
                _employee.LastName = employeeItem.LastName;
                _employee.NickName = employeeItem.NickName;
                //_employee.SSS = employeeItem.SSS;
                //_employee.Tin = employeeItem.Tin;
                //_employee.PhilHealth = employeeItem.PhilHealth;
                //_employee.PagIbig = employeeItem.PagIbig;
                _employee.PrimarySchoolName = employeeItem.PrimarySchoolName;
                _employee.PrimarySchoolPeriod = employeeItem.PrimarySchoolPeriod;
                _employee.SecondarySchoolName = employeeItem.SecondarySchoolName;
                _employee.SecondarySchoolPeriod = employeeItem.SecondarySchoolPeriod;
                _employee.TertiarySchoolName = employeeItem.TertiarySchoolName;
                _employee.TertiarySchoolPeriod = employeeItem.TertiarySchoolPeriod;
                _employee.CollegeDegree = employeeItem.CollegeDegree;
                _employee.PositionId = employeeItem.PositionId;
                _employee.DetachmentId = employeeItem.DetachmentId;
                _employee.SupervisorId = employeeItem.SupervisorId;                
                if(DateTime.TryParse(employeeItem.DateOfBirth,out tempDate))
                    _employee.DateOfBirth = tempDate;
                _employee.PlaceOfBirth = employeeItem.PlaceOfBirth;
                _employee.Religion = employeeItem.Religion;
                _employee.Qualifier = employeeItem.Qualifier;
                _employee.Height = employeeItem.Height;
                _employee.Weight = employeeItem.Weight;
                _employee.Gender = employeeItem.Gender;
                _employee.CivilStatus = employeeItem.CivilStatus;
                _employee.YearsMarried = employeeItem.YearsMarried;
                _employee.ATMno = employeeItem.ATMno;

                _employee.SetStatus(employeeItem.EmployedStatus);
                _employeeService.Update(_employee);
            }
            else
            {
                //Add New
                isAdded = true;
                _employee = new Employee
                {
                    FirstName = employeeItem.FirstName,
                    MiddleName = employeeItem.MiddleName,
                    LastName = employeeItem.LastName,
                    NickName = employeeItem.NickName,
                    //SSS = employeeItem.SSS,
                    //Tin = employeeItem.Tin,
                    //PhilHealth = employeeItem.PhilHealth,
                    //PagIbig = employeeItem.PagIbig,
                    PrimarySchoolName = employeeItem.PrimarySchoolName,
                    PrimarySchoolPeriod = employeeItem.PrimarySchoolPeriod,
                    SecondarySchoolName = employeeItem.SecondarySchoolName,
                    SecondarySchoolPeriod = employeeItem.SecondarySchoolPeriod,
                    TertiarySchoolName = employeeItem.TertiarySchoolName,
                    TertiarySchoolPeriod = employeeItem.TertiarySchoolPeriod,
                    CollegeDegree = employeeItem.CollegeDegree,
                    PositionId = employeeItem.PositionId,
                    DetachmentId = employeeItem.DetachmentId,
                    SupervisorId = employeeItem.SupervisorId,     
                    PlaceOfBirth = employeeItem.PlaceOfBirth,
                    Religion = employeeItem.Religion,
                    Qualifier = employeeItem.Qualifier,
                    Height = employeeItem.Height,
                    Weight = employeeItem.Weight,
                    Gender = employeeItem.Gender,
                    CivilStatus = employeeItem.CivilStatus,
                    YearsMarried = employeeItem.YearsMarried,
                    ATMno = employeeItem.ATMno
                };

                if(DateTime.TryParse(employeeItem.DateOfBirth,out tempDate))
                    _employee.DateOfBirth = tempDate;
                _employee.SetStatus(employeeItem.EmployedStatus);
                _employeeService.Add(_employee);
            }            
            var status = _employeeService.Save();
            employeeItem.Id = _employee.Id;
            employeeItem.EmployeeCode = _employee.EmployeeCode;

            string json = JsonConvert.SerializeObject(
                new
                {
                    Success = status,
                    IsAdded = isAdded,
                    EmployeeItem = employeeItem
                });
            return json;
        }

        [WebMethod]
        public string DeleteEmployee(int Id)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            _employeeService.Delete(Id);
            var status = _employeeService.Save();
            string json = JsonConvert.SerializeObject(new { Success = status });
            return json;
        }

        [WebMethod]
        public List<EmployeeSearchObj> FetchEmployees(string employeeName)
        {
            var fetchData = _employeeService.GetAll()
                            .Where(x => (x.FirstName + " " + x.LastName).ToLower().Contains(employeeName.ToLower()))
                            .Select(x => new EmployeeSearchObj { Id=x.Id, EmployeeName = x.FirstName + " " +  x.LastName });
            return fetchData.ToList();
        }
        [WebMethod]
        public string FetchPositionBySectorId(int sectorId)
        {
            var fetchData = _detachmentService.GetAll()
                            .Where(x => x.SectorId == sectorId)
                            .Select(x => new
                            {
                                Value = x.PositionId,
                                Text = x.Position.Code
                            }).ToList();
            return JsonConvert.SerializeObject(fetchData);       
        }
        #endregion

        #region Positions
        [WebMethod]
        public string AddPosition(PositionObj positionItem)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            var position = positionItem.Id > 0 ? _positionService.GetById(positionItem.Id) : null;
            bool isAdded;
            if (position != null)
            {
                //Update
                isAdded = false;
                position.Code = positionItem.Code;
                position.Description = positionItem.Description;
                position.Incentive = positionItem.Incentive;
                position.Retirement = positionItem.Retirement;
                position.UniformAllowance = positionItem.UniformAllowance;
                _positionService.Update(position);
            }
            else
            {
                //Add New
                isAdded = true;
                position = new Position
                {
                    Code = positionItem.Code,
                    Description = positionItem.Description,
                    Incentive = positionItem.Incentive,
                    Retirement = positionItem.Retirement,
                    UniformAllowance = positionItem.UniformAllowance
                };
                _positionService.Add(position);
            }
            
            var status = _positionService.Save();
            positionItem.Id = position.Id;

            string json = JsonConvert.SerializeObject(
                new
                {
                    Success = status,
                    IsAdded = isAdded,
                    PositionItem = positionItem
                });
            return json;
        }

        [WebMethod]
        public string DeletePosition(int Id)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            _positionService.Delete(Id);
            var status = _positionService.Save();
            string json = JsonConvert.SerializeObject(new { Success = status });
            return json;
        }

        #endregion

        #region Clients
        [WebMethod]
        public string AddClient(ClientObj clientItem)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            var newClient = new Client
            {
                Code = clientItem.Code,
                FirmName = clientItem.FirmName,
                Address = clientItem.Address
            };
            _clientService.Add(newClient);

            var status = _clientService.Save();
            string json = JsonConvert.SerializeObject(new { Success = status, newItem = newClient });
            return json;
        }
        #endregion

        #region Adjustment

        [WebMethod]
        public string AddAdjustment(AdjustmentObj adjustmentItem)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            var adjustment = adjustmentItem.Id > 0 ? _adjustmentService.GetById(adjustmentItem.Id) : null;
            bool isAdded;
            if (adjustment != null)
            {
                //Update
                isAdded = false;
                adjustment.Code = adjustmentItem.Code;
                adjustment.Description = adjustmentItem.Description;
                adjustment.AccountType = adjustmentItem.intAccountType;
                adjustment.AccountSignEnum = (AccountSign)adjustmentItem.intAccountSign;                
                _adjustmentService.Update(adjustment);
            }
            else
            {
                //Add New
                isAdded = true;
                adjustment = new Adjustment
                {
                    Code = adjustmentItem.Code,
                    Description = adjustmentItem.Description,
                    AccountType = adjustmentItem.intAccountType,
                    AccountSignEnum = (AccountSign)adjustmentItem.intAccountSign               
                };
                _adjustmentService.Add(adjustment);
            }
            adjustmentItem.Id = adjustment.Id;
            adjustmentItem.strAccountType = ((AccountType)adjustment.AccountType).GetDescription();
            adjustmentItem.strAccountSign = adjustment.IsAdditional ? "add(+)" : "minus(-)";

            var status = _adjustmentService.Save();
            string json = JsonConvert.SerializeObject(
                new
                {
                    Success = status,
                    IsAdded = isAdded,
                    AdjustmentItem = adjustmentItem
                });
            return json;
        }

        [WebMethod]
        public string DeleteAdjustment(int Id)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            _adjustmentService.Delete(Id);
            var status = _adjustmentService.Save();
            string json = JsonConvert.SerializeObject(new { Success = status });
            return json;
        }
        
        #endregion

        #region Sectors

        [WebMethod]
        public string AddSector(SectorObj sectorItem)
        {
            //string userName = UserHelper.ValidateAndGetUserName();

            var sector = sectorItem.Id > 0 ? _sectorService.GetById(sectorItem.Id) : null;
            bool isAdded;
            if (sector != null)
            {
                //Update
                isAdded = false;
                sector.Name = sectorItem.Name;
                //sector.PositionId = sectorItem.PositionId;
                //sector.ClientId = sectorItem.ClientId;
                //sector.WorkHours = sectorItem.WorkHours;
                //sector.RatePerDay = sectorItem.RatePerDay;
                //sector.RatePerHour = sectorItem.RatePerHour;
                _sectorService.Update(sector);
            }
            else
            {
                //Add New
                isAdded = true;
                sector = new Sector
                {
                    Name = sectorItem.Name,
                    //PositionId = sectorItem.PositionId,
                    //ClientId = sectorItem.ClientId,
                    //WorkHours = sectorItem.WorkHours,
                    //RatePerDay = sectorItem.RatePerDay,
                    //RatePerHour = sectorItem.RatePerHour
                };
                _sectorService.Add(sector);
            }
            sectorItem.Id = sector.Id;

            var status = _sectorService.Save();
            string json = JsonConvert.SerializeObject(
                new
                {
                    Success = status,
                    IsAdded = isAdded,
                    SectorItem = sectorItem
                });
            return json;
        }

        //[WebMethod]
        //public string DeleteSector(int Id)
        //{
        //    //string userName = UserHelper.ValidateAndGetUserName();

        //    _adjustmentService.Delete(Id);
        //    var status = _adjustmentService.Save();
        //    string json = JsonConvert.SerializeObject(new { Success = status });
        //    return json;
        //}

        #endregion

    }

    #region Models
    public class ClientObj
    { 
        public string Code {get; set;}
        public string FirmName { get; set; }
        public string Address { get; set; }
    }

    public class PositionObj
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }        
        public double Incentive { get; set; }        
        public double Retirement { get; set; }        
        public double UniformAllowance { get; set; }        
    }

    public class AdjustmentObj
    {
        public int Id { get; set; }
        public string Code {get; set;}
        public string Description { get; set; }
        public int intAccountType { get; set; }
        public int intAccountSign { get; set; }

        public string strAccountType { get; set; }
        public string strAccountSign { get; set; }

    }

    public class EmployeeObj
    {
        public int Id { get; set; }

        #region Personal Details

        public string EmployeeCode { get; set; }
        public string FirstName { get; set; }                
        public string MiddleName { get; set; }               
        public string LastName { get; set; }        
        public string Sex { get; set; }
        public string NickName { get; set; }
        public string DateOfBirth { get; set; }       
        public string PlaceOfBirth { get; set; }        
        public string Height { get; set; }        
        public string Weight { get; set; }
        public string Qualifier { get; set; }        
        public string Religion { get; set; }        
        public string SSS { get; set; }        
        public string Tin { get; set; }        
        public string PhilHealth { get; set; }        
        public string PagIbig { get; set; }        
        public string CivilStatus { get; set; }
        public string YearsMarried { get; set; }
        public string Gender { get; set; }        
        public string ATMno { get; set; }
        #endregion

        #region Education
        
        public string PrimarySchoolName { get; set; }        
        public string PrimarySchoolPeriod { get; set; }        
        public string SecondarySchoolName { get; set; }        
        public string SecondarySchoolPeriod { get; set; }        
        public string TertiarySchoolName { get; set; }        
        public string TertiarySchoolPeriod { get; set; }        
        public string CollegeDegree { get; set; }
        #endregion
        
        public int EmployedStatus { get; set; }
        public int PositionId { get; set; }
        public int DetachmentId { get; set; }
        public int SupervisorId { get; set; }
    }

    public class EmployeeSearchObj
    {
        public int Id { get; set; }
        public string EmployeeName { get; set; }
    }

    public class PositionSearchObj
    {
        public int Id { get; set; }
        public string PositionCode { get; set; }
    }

    public class EmployeeCashAdv
    {
        public int Id { get; set; }
        public int EmployeeId { get; set; }
        public double Amount { get; set; }
    }

    public class SectorObj
    {
        public int Id { get; set; }        
        public int PositionId { get; set; }
        public int ClientId { get; set; }
        public string Name { get; set; }
        public double WorkHours { get; set; }
        public double RatePerDay { get; set; }
        public double RatePerHour { get; set; }
    }
    #endregion
}

